package io.finer.erp.jeecg.bas.controller;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import io.finer.erp.jeecg.bas.entity.*;
import io.finer.erp.jeecg.bas.service.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.constant.MaterialConstant;
import org.jeecg.common.system.api.ISysBaseAPI;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.DateUtils;
import org.jeecg.common.util.FillRuleUtil;
import org.jeecg.common.util.oConvertUtils;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import cn.hutool.core.util.NumberUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;

 /**
 * @Description: 车间任务/订单
 * @Author: jeecg-boot
 * @Date:   2020-09-02
 * @Version: V1.0
 */
@Api(tags="车间任务/订单")
@RestController
@RequestMapping("/bas/zzShoporder")
@Slf4j
public class ZzShoporderController extends JeecgController<ZzShoporder, IZzShoporderService> {

	@Autowired
	private IZzShoporderService zzShoporderService;

	@Autowired
	private IZrkOrderProcessService zrkOrderProcessService;
	
	@Autowired
	private IZrkQzOrderService zrkQzOrderService;
	@Autowired
	private IZzDeviceTypeService zzDeviceTypeService;
	@Autowired
	private IZrkQzOrderInfoService infoService;
	@Autowired
	private IBasMaterialService materialService;
	@Autowired
	private IZrkShoporderService zrkShoporderService;
	@Autowired
	private IZrkOrderProductService zrkOrderProductService;
	@Autowired
    private  IBasMaterialCategoryService materialCategoryService;
    @Autowired
    private IBasCustomerService customerService;
    @Autowired
    private ISysBaseAPI basApi;

	/*---------------------------------主表处理-begin-------------------------------------*/

	/**
	 * 分页列表查询
	 * @param zzShoporder
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "车间任务/订单-分页列表查询")
	@ApiOperation(value="车间任务/订单-分页列表查询", notes="车间任务/订单-分页列表查询")
	@GetMapping(value = "/list")
	public Result<?> queryPageList(ZzShoporder zzShoporder,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<ZzShoporder> queryWrapper = QueryGenerator.initQueryWrapper(zzShoporder, req.getParameterMap());
		Page<ZzShoporder> page = new Page<ZzShoporder>(pageNo, pageSize);
		IPage<ZzShoporder> pageList = zzShoporderService.page(page, queryWrapper);
		return Result.ok(pageList);
	}

	 @AutoLog(value = "复合切张任务/订单-分页列表查询")
	 @ApiOperation(value="复合切张任务/订单-分页列表查询", notes="车间切张任务/复合订单-分页列表查询")
	 @GetMapping(value = "/listByProcess/{gxId}")
//	 @GetMapping(value = "/listByProcess")
	public Result<?> FhList(ZzShoporder zzShoporder,
							@RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
							@RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
							HttpServletRequest req, @PathVariable("gxId") String gxId){

		 QueryWrapper<ZzShoporder> queryWrapper = QueryGenerator.initQueryWrapper(zzShoporder, req.getParameterMap());
		 Page<ZzShoporder> page = new Page<ZzShoporder>(pageNo, pageSize);

//		根据传递的这个工序id判断是复合还是切张
		 //切张--普通切张id或者大型机器切张id
		 if(gxId.equals(MaterialConstant.PROCESS_CUTTING_NORMAL)
				 || gxId.equals(MaterialConstant.PROCESS_CUTTING_BIG) ) {
			 //如果是普通切张id或者大型机器切张id----查询大型机器切张工序id和普通切张工序id的数据
		 	List<String> qz= new ArrayList<>();
		 	qz.add(MaterialConstant.PROCESS_CUTTING_NORMAL);
		 	qz.add(MaterialConstant.PROCESS_CUTTING_BIG);
		 	queryWrapper.in("process_id",qz);

		 }else if(gxId.equals(MaterialConstant.PROCESS_COMPOUND)){
		 	//如果是复合工序id---查询复合工序id的数据
			 queryWrapper.eq("process_id",MaterialConstant.PROCESS_COMPOUND);
		 }
		IPage<ZzShoporder> pageList =zzShoporderService.page(page,queryWrapper);

		return Result.ok(pageList);

	}
	 @AutoLog(value = "制胶任务/订单-分页列表查询")
	 @ApiOperation(value="制胶任务/订单-分页列表查询", notes="车间制胶任务/制胶订单-分页列表查询")
	 @GetMapping(value = "/listByProcessZj")
	 public Result<?> ZjList(ZzShoporder zzShoporder,
							 @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
							 @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
							 HttpServletRequest req){

		 QueryWrapper<ZzShoporder> queryWrapper = QueryGenerator.initQueryWrapper(zzShoporder, req.getParameterMap());
		 Page<ZzShoporder> page = new Page<ZzShoporder>(pageNo, pageSize);
		 queryWrapper.eq("process_id",MaterialConstant.PROCESS_ZJ);
		 IPage<ZzShoporder> pageList =zzShoporderService.page(page,queryWrapper);
		 return Result.ok(pageList);
	 }

	 /**
     *   添加
     * @param zzShoporder
     * @return
     */
    @AutoLog(value = "车间任务/订单-添加")
    @ApiOperation(value="车间任务/订单-添加", notes="车间任务/订单-添加")
	@PostMapping(value = "/add")
    public Result<?> add(@RequestBody ZzShoporder zzShoporder) {
    	//制胶任务单添加
		zzShoporder.setProcessId(MaterialConstant.PROCESS_ZJ);
       BasMaterialCategory category= materialCategoryService.getById(zzShoporder.getCategoryId());
       if(category!=null ) {
           zzShoporder.setWoPartname(category.getName());
       }else{
           zzShoporder.setWoPartname("");
       }
       zzShoporder.setWoUnit("1318447754322341890");
       BasCustomer basCustomer=customerService.getById(zzShoporder.getWoUnit());
       if(basCustomer!=null){
           zzShoporder.setCustomerName(basCustomer.getName());
       }else{
           zzShoporder.setCustomerName("");
       }
		zzShoporder.setIsPush(0);
		zzShoporder.setOrderName("制胶任务单手动添加");
		zzShoporder.setWoCode(basApi.getNoByCode("work_zj_no"));
		zzShoporder.setWoPartcode(basApi.getNoByCode("productNO"));
		zzShoporder.setWoType("1");
		zzShoporder.setWoPriority(2);
		zzShoporder.setWoStatus(1);
        zzShoporderService.save(zzShoporder);
        return Result.ok("添加成功！");
    }

    /**
     *  编辑
     * @param zzShoporder
     * @return
     */
    @AutoLog(value = "车间任务/订单-编辑")
    @ApiOperation(value="车间任务/订单-编辑", notes="车间任务/订单-编辑")
    @PutMapping(value = "/edit")
    public Result<?> edit(@RequestBody ZzShoporder zzShoporder) {
		boolean bol= zzShoporderService.updateById(zzShoporder);
		if(!bol){
			return Result.error("编辑失败");
		}
        return Result.ok("编辑成功!");
    }


	 @AutoLog(value = "复合/切张任务/订单-通过id删除")
	 @ApiOperation(value="复合/切张任务/订单-通过id删除", notes="复合/切张任务/订单-通过id删除")
	 @DeleteMapping(value = "/deleteProcess")
	 public Result<?> deleteProcess(@RequestParam(name="id",required=true) String id) {
		boolean bol=zzShoporderService.removeById(id);
		if(!bol){
			return Result.error("删除失败");
		}
		 return Result.ok("删除成功!");
	 }


	 /**
	  * 根据id查询详情
	  * @param id
	  * @return
	  */

	 @AutoLog(value = "复合/切张任务/订单-详情")
	 @ApiOperation(value="复合/切张任务/订单-通过id详情", notes="复合/切张任务/订单-详情")
	 @GetMapping(value = "/detail")
	 public Result<?> Detail(@RequestParam(name="id",required=true) String id) {
		ZzShoporder zzShoporder= zzShoporderService.getById(id);
	 	if(zzShoporder.equals(null)){
			return Result.error("未找到对应数据");
		}
		 return Result.ok(zzShoporder);
	 }

	 /**
     * 通过id删除
     * @param id
     * @return
     */
    @AutoLog(value = "车间任务/订单-通过id删除")
    @ApiOperation(value="车间任务/订单-通过id删除", notes="车间任务/订单-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name="id",required=true) String id) {
        zzShoporderService.delMain(id);
        return Result.ok("删除成功!");
    }

    /**
     * 批量删除
     * @param ids
     * @return
     */
    @AutoLog(value = "车间任务/订单-批量删除")
    @ApiOperation(value="车间任务/订单-批量删除", notes="车间任务/订单-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
        this.zzShoporderService.delBatchMain(Arrays.asList(ids.split(",")));
        return Result.ok("批量删除成功!");
    }

    /**
     * 导出
     * @return
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, ZzShoporder zzShoporder) {
        return super.exportXls(request, zzShoporder, ZzShoporder.class, "车间任务/订单");
    }

    /**
     * 导入
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, ZzShoporder.class);
    }

	 /**
	  * 任务单撤单
	  * @param id
	  * @return
	  */
    @GetMapping("recall")
    @AutoLog(value = "任务单撤单")
	public Result<?> recall(String id){

		return zzShoporderService.recall(id);
	}
    
    /**
	  * 任务单直接出库撤单
	  * @param id
	  * @return
	  */
   @GetMapping("recallDelivery")
   @AutoLog(value = "任务单直接出库撤单")
	public Result<?> recallDelivery(String id){
		return zzShoporderService.recallDelivery(id);
	}

	 /**
	  * 切张任务单撤单分切任务单
	  * @param id
	  * @return
	  */
 	@GetMapping("recallQz")
 	@AutoLog(value = "切张任务单撤单分切任务单")
	public Result<?> recallQzOrFq(String id){
		return zzShoporderService.recallQzOrFq(id);
	}


	/*---------------------------------主表处理-end-------------------------------------*/
	

    /*--------------------------------子表处理-车间任务单工序机器分配-begin----------------------------------------------*/
	/**
	 * 通过主表ID查询
	 * @return
	 */
	@AutoLog(value = "车间任务单工序机器分配-通过主表ID查询")
	@ApiOperation(value="车间任务单工序机器分配-通过主表ID查询", notes="车间任务单工序机器分配-通过主表ID查询")
	@GetMapping(value = "/listZrkOrderProcessByMainId")
    public Result<?> listZrkOrderProcessByMainId(ZrkOrderProcess zrkOrderProcess,
                                                    @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                    @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                    HttpServletRequest req) {
        QueryWrapper<ZrkOrderProcess> queryWrapper = QueryGenerator.initQueryWrapper(zrkOrderProcess, req.getParameterMap());
        Page<ZrkOrderProcess> page = new Page<ZrkOrderProcess>(pageNo, pageSize);
        IPage<ZrkOrderProcess> pageList = zrkOrderProcessService.page(page, queryWrapper);
        return Result.ok(pageList);
    }

	/**
	 * 添加
	 * @param zrkOrderProcess
	 * @return
	 */
	@SuppressWarnings("unused")
	@AutoLog(value = "车间任务单工序机器分配-添加")
	@ApiOperation(value="车间任务单工序机器分配-添加", notes="车间任务单工序机器分配-添加")
	@PostMapping(value = "/addZrkOrderProcess")
	//TODO
	public Result<?> addZrkOrderProcess(@RequestBody ZrkOrderProcess zrkOrderProcess) {
		//根据前端传过来的数据解析ID {id:["1301794578965270529"]}
		//根据选中工序ID查询该条工序信息
		ZrkOrderProcess zop = zrkOrderProcessService.getById(zrkOrderProcess.getId());
		//查询主工单信息
		ZzShoporder zzShoporder = zzShoporderService.getById(zop.getOrderId());
		//查询工序信息
		ZzDeviceType zzDeviceType = zzDeviceTypeService.getById(zop.getProcessId());
		//通过生产单关联的销售单获取到客户名称
		String orderNo = zzShoporder.getOrderNo();
		ZrkShoporder zrkShoporder = this.zrkShoporderService.selectByOrderCode(orderNo);
		String customerName = zrkShoporder.getCustomerName();
		String orderProcessId = zrkOrderProcess.getId();
		//判断切张单是否已经生成
		ZrkQzOrder checkOrder = this.zrkQzOrderService.checkByOrderProcessId(orderProcessId);
		boolean flag = checkOrder != null;
		//根据工序生成不同的单据
		if(zzDeviceType.getDeviceTpyeName().indexOf("切张")>0) {
			//确认生成的是切张单
			//生成切张单信息
			ZrkQzOrder zrkQzOrder = new ZrkQzOrder();
			if(null!=zop) {
				//切张单已经存在
				if(flag) {
					return Result.error("切张单已经存在，请不要重复生成！");
				}else {
					//未生成过切张单
					//获取登录用户
					LoginUser sysUser = (LoginUser)SecurityUtils.getSubject().getPrincipal();
					zrkQzOrder.setCreateBy(sysUser.getUsername());//设置操作人为当前登录用户的登录账号
					zrkQzOrder.setCreateTime(DateUtils.getDate());
					zrkQzOrder.setIsFinish(0);
					zrkQzOrder.setMaterialId(zzShoporder.getWoPartname());
					zrkQzOrder.setSpecs(zzShoporder.getSpecs());
					zrkQzOrder.setZrkAmt(zzShoporder.getWoQuantity());
					zrkQzOrder.setIsPush(1);
					zrkQzOrder.setWoDeliverytime(zzShoporder.getWoDeliverytime());
					zrkQzOrder.setProcessId(zop.getProcessId());//设置工序
					zrkQzOrder.setOrderProcessId(zrkOrderProcess.getId());
					//封装物料ID
					String materialName = zzShoporder.getWoPartname();
					String orderCode = zrkShoporder.getOrderCode();
					List<ZrkOrderProduct> productList = zrkOrderProductService.selectByMainId(orderCode);
					if(productList != null && 0 != productList.size()) {
						String mId = null;
						for (ZrkOrderProduct product : productList) {
							String materialId = product.getMaterialId();
							BasMaterial material = materialService.getById(materialId);
							if(material != null && material.getName().equals(materialName)) {
								mId = material.getId();
								break;
							}
							if(product.getProductName().equals(materialName)) {
								mId = product.getMaterialId();
							}
						}
						if(null != mId) {
							zrkQzOrder.setMaterialId(mId);
						} else {
							String materialId = this.materialService.getOneMaterialIdByName(materialName);
							zrkQzOrder.setMaterialId(materialId);
						}
					} else {
						String materialId = this.materialService.getOneMaterialIdByName(materialName);
						zrkQzOrder.setMaterialId(materialId);
					}
					
					zrkQzOrder.setCustomerName(customerName);
					//设置操作人信息
					zrkQzOrder.setOperatorUsers(zop.getUserId());
					//设置操作机器信息
					zrkQzOrder.setMachineId(zop.getDeviceId());
					zrkQzOrderService.save(zrkQzOrder);
					return Result.ok("生成切张单成功！");
				}
			}else {
				return Result.error("未找到切张工序信息！");
			}
		} else if(zzDeviceType.getDeviceTpyeName().contains("复合")) {
			//确认生成的是复合单
			//生成复合单信息
			ZrkQzOrder zrkQzOrder = new ZrkQzOrder();
			if(null!=zop) {
				//复合单已经存在
				if(flag) {
					return Result.error("复合单已经存在，请不要重复生成！");
				}else {
					//未生成过复合单
					//获取登录用户
					LoginUser sysUser = (LoginUser)SecurityUtils.getSubject().getPrincipal();
					zrkQzOrder.setCreateBy(sysUser.getUsername());//设置操作人为当前登录用户的登录账号
					zrkQzOrder.setCreateTime(DateUtils.getDate());
					zrkQzOrder.setIsFinish(0);
					zrkQzOrder.setMaterialId(zzShoporder.getWoPartname());
					zrkQzOrder.setSpecs(zzShoporder.getSpecs());
					zrkQzOrder.setZrkAmt(zzShoporder.getWoQuantity());
					zrkQzOrder.setIsPush(1);
					zrkQzOrder.setWoDeliverytime(zzShoporder.getWoDeliverytime());
					zrkQzOrder.setProcessId(zop.getProcessId());//设置工序
					zrkQzOrder.setOrderProcessId(zrkOrderProcess.getId());
					zrkQzOrder.setCustomerName(customerName);
					//封装物料ID
					String materialName = zzShoporder.getWoPartname();
					String orderCode = zrkShoporder.getOrderCode();
					List<ZrkOrderProduct> productList = zrkOrderProductService.selectByMainId(orderCode);
					if(productList != null && 0 != productList.size()) {
						String mId = null;
						for (ZrkOrderProduct product : productList) {
							String materialId = product.getMaterialId();
							BasMaterial material = materialService.getById(materialId);
							if(material != null && material.getName().equals(materialName)) {
								mId = material.getId();
								break;
							}
							if(product.getProductName().equals(materialName)) {
								mId = product.getMaterialId();
							}
						}
						if(null != mId) {
							zrkQzOrder.setMaterialId(mId);
						} else {
							String materialId = this.materialService.getOneMaterialIdByName(materialName);
							zrkQzOrder.setMaterialId(materialId);
						}
					} else {
						String materialId = this.materialService.getOneMaterialIdByName(materialName);
						zrkQzOrder.setMaterialId(materialId);
					}
					
					//设置操作人信息
					zrkQzOrder.setOperatorUsers(zop.getUserId());
					//设置操作机器信息
					zrkQzOrder.setMachineId(zop.getDeviceId());
					zrkQzOrderService.save(zrkQzOrder);
					return Result.ok("生成复合单成功！");
				}
			}else {
				return Result.error("未找到复合工序信息！");
			}			
		}
		else {
			return Result.error("请选择对应工序生成相关单据！");
		}
		
	}
	
	
	@SuppressWarnings("unused")
	@AutoLog(value = "车间任务单工序机器分配-添加-分切单")
	@ApiOperation(value="车间任务单工序机器分配-添加-分切单", notes="车间任务单工序机器分配-添加-分切单")
	@PostMapping(value = "/addZrkOrderProcessFQ")
	public Result<?> addZrkOrderProcessFQ(@RequestBody ZrkOrderProcess zrkOrderProcess){
		//TODO
		//根据前端传过来的数据解析ID {id:["1301794578965270529"]}
		//根据选中工序ID查询该条工序信息
		ZrkOrderProcess zop = zrkOrderProcessService.getById(zrkOrderProcess.getId());
		//查询主工单信息
		ZzShoporder zzShoporder = zzShoporderService.getById(zop.getOrderId());
		//查询工序信息
		ZzDeviceType zzDeviceType = zzDeviceTypeService.getById(zop.getProcessId());
		//通过生产单关联的销售单获取到客户名称
		String orderNo = zzShoporder.getOrderNo();
		ZrkShoporder zrkShoporder = this.zrkShoporderService.selectByOrderCode(orderNo);
		String customerName = zrkShoporder.getCustomerName();
		String orderProcessId = zrkOrderProcess.getId();
		//判断切张单是否已经生成
		ZrkQzOrder checkOrder = this.zrkQzOrderService.checkByOrderProcessId(orderProcessId);
		if(zzDeviceType.getDeviceTpyeName().contains("分切")) {
			Integer length = zop.getFqLength();
			String fqParam = zop.getFqParams();
			String bcpID = zop.getFqCategory();
			if (length == null) {
				return Result.error("请填写分切长度");
			}
			if(null==fqParam) {
				return Result.error("请填写分切参数");
			}
			if(null==bcpID) {
				return Result.error("请选择分切半成品");
			}
			if (StringUtils.isBlank(fqParam.trim()) || StringUtils.isBlank(bcpID.trim())) {
				return Result.error("请填写分切参数");
			}
			if (StringUtils.isBlank(bcpID.trim())) {
				return Result.error("请选择分切半成品");
			}
			
			//确认生成的是分切单
			//生成分切单信息
			ZrkQzOrder zrkQzOrder = new ZrkQzOrder();
			if(null != zop) {
				//分切单已经存在
				if(checkOrder != null) {
					return Result.error("分切单已经存在，请不要重复生成！");
				} else {
					//未生成过分切单
					//获取登录用户
					LoginUser sysUser = (LoginUser)SecurityUtils.getSubject().getPrincipal();
					zrkQzOrder.setCreateBy(sysUser.getUsername());//设置操作人为当前登录用户的登录账号
					zrkQzOrder.setCreateTime(DateUtils.getDate());
					zrkQzOrder.setIsFinish(0);
					zrkQzOrder.setSpecs(fqParam);
					zrkQzOrder.setZrkAmt(length);
					zrkQzOrder.setIsPush(1);
					zrkQzOrder.setProductNum(NumberUtil.toBigDecimal(zzShoporder.getWoQuantity()));	
					zrkQzOrder.setWoDeliverytime(zzShoporder.getWoDeliverytime());
					zrkQzOrder.setProcessId(zop.getProcessId());//设置工序
					zrkQzOrder.setOrderProcessId(zrkOrderProcess.getId());
					//设置操作人信息
					zrkQzOrder.setOperatorUsers(zop.getUserId());//-----By:heckerstone 2020-10-14
					//设置操作机器信息
					zrkQzOrder.setMachineId(zop.getDeviceId());//-----By:heckerstone 2020-10-14
					zrkQzOrder.setCustomerName(customerName);
					zrkQzOrderService.save(zrkQzOrder);
					//获取胶水和底板纸的供应商
					String paperSUpplier = zzShoporder.getPaperSupplier();
					String glueSupplier = zzShoporder.getGlueSupplier();
					//将分切单中的materialID替换掉
					BasMaterial material = materialService.getOneMaterialByCategory(bcpID);
					if(null != material) {
						zrkQzOrder.setMaterialId(material.getId());
						zrkQzOrderService.updateById(zrkQzOrder);
					} else {
						material = materialService.createMaterialByCategory(bcpID);
						zrkQzOrder.setMaterialId(material.getId());
						zrkQzOrderService.updateById(zrkQzOrder);
					}
					
					//生成分切单时对应在临时表中存储分切的物料信息
					String[] strs = fqParam.split("\\+");
					Date date = DateUtils.getDate();
					for (String string : strs) {
						BigDecimal width = new BigDecimal(string);
						ZrkQzOrderInfo info = new ZrkQzOrderInfo();
						info.setWidth(width);
						info.setOrderId(zzShoporder.getId());
						info.setFqId(zrkQzOrder.getId());
						info.setCreateTime(date);
						info.setPid(zrkQzOrder.getMaterialId());
						infoService.save(info);
					}
					return Result.ok("生成分切单成功！");
				}
			} else {
				return Result.error("未找到分切工序信息！");
			}
		} else {
			return Result.error("请选择对应工序生成相关单据！");
		}
	}
	
	/**
	 * 添加
	 * @param zrkOrderProcess
	 * @return
	 */
	@AutoLog(value = "车间任务单工序机器分配-生成切张单")
	@ApiOperation(value="车间任务单工序机器分配-生成切张单", notes="车间任务单工序机器分配-生成切张单")
	@PostMapping(value = "/generateQZOrder")
	public Result<?> generateQZOrder(@RequestBody ZrkOrderProcess zrkOrderProcess) {
		zrkOrderProcessService.save(zrkOrderProcess);
		return Result.ok("添加成功！");
	}

	/**
	 * 编辑
	 * @param zrkOrderProcess
	 * @return
	 */
	@AutoLog(value = "车间任务单工序机器分配-编辑")
	@ApiOperation(value="车间任务单工序机器分配-编辑", notes="车间任务单工序机器分配-编辑")
	@PutMapping(value = "/editZrkOrderProcess")
	public Result<?> editZrkOrderProcess(@RequestBody ZrkOrderProcess zrkOrderProcess) {
		//编辑时判断是否改动了操作人信息，如果改动则同步更新切张/分切单中的操作人信息
		//查询数据库原有信息
		ZrkOrderProcess zop=zrkOrderProcessService.getById(zrkOrderProcess.getId());
		//比对是否改动了操作人
		if(!(zop.getUserId().equals(zrkOrderProcess.getUserId()))) {
			//确认改动了操作人，同步更新切张/分切单中的操作人信息
			QueryWrapper<ZrkQzOrder> queryWrapper=new QueryWrapper<ZrkQzOrder>();
			queryWrapper.eq("order_process_id", zrkOrderProcess.getId());//根据关联主键查询
			ZrkQzOrder zoo=zrkQzOrderService.getOne(queryWrapper.last("LIMIT 1"));//确保取出一条数据
			zoo.setOperatorUsers(zrkOrderProcess.getUserId());//设置修改后的操作人信息
			zrkQzOrderService.updateById(zoo);//持久化数据更新
		}
		//判断是否修改了机器信息
		if(!(zop.getDeviceId().equals(zrkOrderProcess.getDeviceId()))) {
			//确认修改了机器信息
			QueryWrapper<ZrkQzOrder> queryWrapper=new QueryWrapper<ZrkQzOrder>();
			queryWrapper.eq("order_process_id", zrkOrderProcess.getId());//根据关联主键查询
			ZrkQzOrder zoo=zrkQzOrderService.getOne(queryWrapper.last("LIMIT 1"));//确保取出一条数据
			zoo.setMachineId(zrkOrderProcess.getDeviceId());
			zrkQzOrderService.updateById(zoo);//持久化数据更新
		}
		zrkOrderProcessService.updateById(zrkOrderProcess);
		return Result.ok("编辑成功!");
	}
	/**
	 * 通过id删除
	 * @param id
	 * @return
	 */
	@AutoLog(value = "车间任务单工序机器分配-通过id删除")
	@ApiOperation(value="车间任务单工序机器分配-通过id删除", notes="车间任务单工序机器分配-通过id删除")
	@DeleteMapping(value = "/deleteZrkOrderProcess")
	public Result<?> deleteZrkOrderProcess(@RequestParam(name="id",required=true) String id) {
		zrkOrderProcessService.removeById(id);
		return Result.ok("删除成功!");
	}

	/**
	 * 批量删除
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "车间任务单工序机器分配-批量删除")
	@ApiOperation(value="车间任务单工序机器分配-批量删除", notes="车间任务单工序机器分配-批量删除")
	@DeleteMapping(value = "/deleteBatchZrkOrderProcess")
	public Result<?> deleteBatchZrkOrderProcess(@RequestParam(name="ids",required=true) String ids) {
	    this.zrkOrderProcessService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.ok("批量删除成功!");
	}

    /**
     * 导出
     * @return
     */
    @RequestMapping(value = "/exportZrkOrderProcess")
    public ModelAndView exportZrkOrderProcess(HttpServletRequest request, ZrkOrderProcess zrkOrderProcess) {
		 // Step.1 组装查询条件
		 QueryWrapper<ZrkOrderProcess> queryWrapper = QueryGenerator.initQueryWrapper(zrkOrderProcess, request.getParameterMap());
		 LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

		 // Step.2 获取导出数据
		 List<ZrkOrderProcess> pageList = zrkOrderProcessService.list(queryWrapper);
		 List<ZrkOrderProcess> exportList = null;

		 // 过滤选中数据
		 String selections = request.getParameter("selections");
		 if (oConvertUtils.isNotEmpty(selections)) {
			 List<String> selectionList = Arrays.asList(selections.split(","));
			 exportList = pageList.stream().filter(item -> selectionList.contains(item.getId())).collect(Collectors.toList());
		 } else {
			 exportList = pageList;
		 }

		 // Step.3 AutoPoi 导出Excel
		 ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
		 mv.addObject(NormalExcelConstants.FILE_NAME, "车间任务单工序机器分配"); //此处设置的filename无效 ,前端会重更新设置一下
		 mv.addObject(NormalExcelConstants.CLASS, ZrkOrderProcess.class);
		 mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("车间任务单工序机器分配报表", "导出人:" + sysUser.getRealname(), "车间任务单工序机器分配"));
		 mv.addObject(NormalExcelConstants.DATA_LIST, exportList);
		 return mv;
    }

    /**
     * 导入
     * @return
     */
    @RequestMapping(value = "/importZrkOrderProcess/{mainId}")
    public Result<?> importZrkOrderProcess(HttpServletRequest request, HttpServletResponse response, @PathVariable("mainId") String mainId) {
		 MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		 Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
		 for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
			 MultipartFile file = entity.getValue();// 获取上传文件对象
			 ImportParams params = new ImportParams();
			 params.setTitleRows(2);
			 params.setHeadRows(1);
			 params.setNeedSave(true);
			 try {
				 List<ZrkOrderProcess> list = ExcelImportUtil.importExcel(file.getInputStream(), ZrkOrderProcess.class, params);
				 for (ZrkOrderProcess temp : list) {
                    temp.setOrderId(mainId);
				 }
				 long start = System.currentTimeMillis();
				 zrkOrderProcessService.saveBatch(list);
				 log.info("消耗时间" + (System.currentTimeMillis() - start) + "毫秒");
				 return Result.ok("文件导入成功！数据行数：" + list.size());
			 } catch (Exception e) {
				 log.error(e.getMessage(), e);
				 return Result.error("文件导入失败:" + e.getMessage());
			 } finally {
				 try {
					 file.getInputStream().close();
				 } catch (IOException e) {
					 e.printStackTrace();
				 }
			 }
		 }
		 return Result.error("文件导入失败！");
    }

    /*--------------------------------子表处理-车间任务单工序机器分配-end----------------------------------------------*/




}
